﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using GeneralDFS.BusinessLogical;
using GeneralDFS.BusinessLogical.Config;
using GeneralDFS.BusinessLogical.Nodes;
using GeneralDFS.BusinessLogical.RemoteObject;
using GeneralDFS.Common;
using GeneralDFS.Common.IO;
using GeneralDFS.Common.Network;
using GeneralDFS.DataEntity.Config;
using GeneralDFS.DataEntity.Nodes;

namespace GeneralDFS.Client
{
    public class Client
    {
        private ConfigCenter _configCenter;

        private void Init()
        {
            LogUtil.Setup();//初始化日志组件
            _configCenter = new ConfigCenter(); //初始化配置中心
        }

        public DFSConfig GetConfig()
        {
            return _configCenter.GetConfig();
        }

        public NameNodeInfo FindNameNode(String src)
        {
            var hash = DFSUtils.GetHash(PathHelper.GetParentPath(src));
            var remoteObject = NameNode.GetInstance(_configCenter.GetFirstConfig().GetNodeInfo());
            if (NameNode.IsInstanceValid(remoteObject))
            {
                return remoteObject.FindSuccessor(hash);
            }
            return null;
        }

        public NameNodeRemoteObject GetRemoteObjectDirect(String src)
        {
            var nameNodeInfo = FindNameNode(src);
            if (nameNodeInfo != null)
                return NameNode.GetInstance(nameNodeInfo);
            throw new Exception("Can not get remoteObject");
        }

        public Client()
        {
            Init();
        }

        public void Close()
        {
            GC.Collect();
        }
    }
}